const express = require('express');
const router = express.Router();
const {Course, Category, User,Chapter} = require('../../models');
const {Op} = require('sequelize');
const { NotFoundError } = require('../../utils/errors');
const { Success, failure } = require('../../utils/responses');

//获取所有课程列表
router.get('/', async (req, res) => {
    try {
        const query = req.query;
        //分页查询需要的参数
        const currentPage = Math.abs(query.currentPage) || 1;
        const pageSize = Math.abs(query.pageSize) || 10;
        const offset = (currentPage - 1) * pageSize;

        const condition = {
            ...getCondition(),
            order: [["id", "DESC"]],
            offset: offset,
            limit: pageSize
        };
        //模糊搜索
        if (query.categoryId) {
            condition.where = {
                categoryId: {
                    [Op.eq]: query.categoryId
                }
            };
        }

        if (query.userId) {
            condition.where = {
                userId: {
                    [Op.eq]: query.userId
                }
            };
        }

        if (query.name) {
            condition.where = {
                name: {
                    [Op.like]: `%${query.name}%`
                }
            };
        }

        if (query.recommended) {
            condition.where = {
                recommended: {
                    // 需要转布尔值
                    [Op.eq]: query.recommended === 'true'
                }
            };
        }

        if (query.introductory) {
            condition.where = {
                introductory: {
                    [Op.eq]: query.introductory === 'true'
                }
            };
        }


        const courses = await Course.findAndCountAll(condition);
        Success(res, '课程查询成功', {
            rows: courses.rows,
            pagination: {
                total: courses.count,
                currentPage: currentPage,
                pageSize: pageSize
            }
        });
    } catch (err) {
        failure(res, err);
    }
});
//获取指定课程
router.get('/:id', async (req, res) => {
    try {
        const course = await GetCourse(req);
        Success(res, '获取课程成功', course);
    } catch (err) {
        failure(res, err);
    }
});
//创建课程
router.post('/', async (req, res) => {
    try {

        //白名单过滤
        const body = FilterBody(req);
        const course = await Course.create(body);

        Success(res, '创建课程成功', course, 201);
    } catch (error) {
        console.log("错误信息：", error);

        failure(res, error);

    }
});
//更新课程
router.put('/:id', async (req, res) => {
    try {
        const course = await GetCourse(req);
        await course.update(req.body);
        Success(res, '更新成功！', course, 200)
    } catch (err) {
        failure(res, err);
    }
});

//删除课程
router.delete('/:id', async (req, res) => {
    try {
        const course = await GetCourse(req);
        const chapterCount = await Chapter.count({where:{courseId:req.params.id}});
        if (chapterCount>0) {
            throw new Error('删除失败，不能删除还有章节的课程');
        }
        await course.destroy();
        Success(res, '删除成功');

    } catch (err) {
        failure(res, err);
    }
});


/**
 * 白名单过滤
 * @param req
 * @returns {{image: ({type: *, validate: {isUrl: {msg: string}}}|{type: *}|*), name, introductory: (boolean|*), userId: (number|*), categoryId: (number|*), content: (string|string|DocumentFragment|*), recommended: (boolean|*)}}
 * @constructor
 */
function FilterBody(req) {
    return {
        categoryId: req.body.categoryId,
        userId: req.body.userId,
        name: req.body.name,
        image: req.body.image,
        recommended: req.body.recommended,
        introductory: req.body.introductory,
        content: req.body.content
    };
}

//获取course对象
async function GetCourse(req) {
    const {id} = req.params;
    console.log(id);
    const condition = getCondition();
    const course = await Course.findByPk(id,condition);
    if (!course) {
        throw new NotFoundError(`ID:${id}的课程未找到`);
    }
    return course;
}

//获取关联查询条件
function getCondition() {
    return {
        attributes: {
            exclude: ['CategoryId', 'UserId']
        },
        include: [
            {
                model: Category,
                as: 'category',
                attributes: ['id', 'name']
            },
            {
                model: User,
                as: 'user',
                attributes: ['id', 'username', 'avatar']
            }
        ]
    };
}

module.exports = router;